package com.sansan.qiangji.controller.device;

import com.sansan.qiangji.VO.device.BeltVO;
import com.sansan.qiangji.VO.device.ScanVO;
import com.sansan.qiangji.enums.ResultEnum;
import com.sansan.qiangji.exception.ServiceException;
import com.sansan.qiangji.form.device.belt.BeltAddForm;
import com.sansan.qiangji.form.device.scan.ScanAddForm;
import com.sansan.qiangji.form.device.scan.ScanEditForm;
import com.sansan.qiangji.realize.device.ScanReal;
import com.sansan.qiangji.resultVO.ResultVO;
import com.sansan.qiangji.utils.ResultVOUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;
import java.util.Objects;

@CrossOrigin()
@RestController
@RequestMapping("/scan")
@Slf4j
public class ScanController {
    private ScanReal scanReal;

    @Resource
    public void setScanReal(ScanReal scanReal) {
        this.scanReal = scanReal;
    }

    @GetMapping("/list")
    public ResultVO<Object> scanList() {
        List<ScanVO> scanVOS = scanReal.scanList();
        return ResultVOUtil.success(scanVOS);
    }

    @PostMapping("/create")
    public ResultVO<Object> scanCreate(@Valid @RequestBody ScanAddForm scanAddForm, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            log.error("【添加传送带】参数不正确，scanAddForm={}", scanAddForm.toString());
            throw new ServiceException(ResultEnum.PARAM_ERROR.getCode(), Objects.requireNonNull(bindingResult.getFieldError()).getDefaultMessage());
        }
        scanReal.scanCreate(scanAddForm);
        return ResultVOUtil.success(null);
    }

    @PostMapping("/edit")
    public ResultVO<Object> scanEdit(@Valid @RequestBody ScanEditForm scanEditForm, BindingResult bindingResult){
        if (bindingResult.hasErrors()) {
            log.error("【编辑传送带】参数不正确，scanEditForm={}", scanEditForm.toString());
            throw new ServiceException(ResultEnum.PARAM_ERROR.getCode(), Objects.requireNonNull(bindingResult.getFieldError()).getDefaultMessage());
        }
        scanReal.scanEdit(scanEditForm);
        return ResultVOUtil.success(null);
    }

    @PostMapping("/delete")
    public ResultVO<Object> deleteScan(@RequestParam(name = "scanId") Integer scanId) {
        scanReal.deleteScan(scanId);
        return ResultVOUtil.success(null);
    }
}
